/*
 * Copyright (c) 2011 Ondrej Lapacek
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

/**
 * @author      Ondrej Lapacek
 * @version     1.0, 09/12/11
 * @since       1.0
 */

package cz.muni.fi.android.assistivecamera.gallery;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import cz.muni.fi.android.assistivecamera.R;
import cz.muni.fi.android.assistivecamera.texttospeech.SpeechHandler;

public class ExifReader {
	
	private Context ctx;
	private static final String TAG = "Exif Reader";	
	
	public void extractExif(String imagePath, Context ctx) {
	    this.ctx = ctx;
	    
	    try {
	    	String nameOfFile = imagePath.replaceFirst("[.][^.]+$", "");
	    	ShowExif(nameOfFile);
	    } catch (Exception e) {
	        Log.e(TAG, "Unable to extract EXIF metadata from image at " + imagePath, e);
	    }
	}
	
	private void ShowExif(String file) {
		String userComment = null;
		
		String state = Environment.getExternalStorageState();
		if( Environment.MEDIA_MOUNTED.equals(state) ) {
			try{
				File f = new File(file);
				FileInputStream is = new FileInputStream(f);
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				userComment = br.readLine();
			} catch (FileNotFoundException e) {
				Log.w(TAG, "file not found", e);
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (userComment != null) {
		    	userComment = fromBaseCharacters(userComment);
		    	try {
					JSONArray recs = new JSONArray(userComment);
					int counter = 0;
					for (int i = 0; i < recs.length(); i++) {
					    JSONObject row = recs.getJSONObject(i);
					    
					    SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.building) + " " + ++counter, 1, 1);
					    String[] tags = ctx.getResources().getStringArray(R.array.tags);
					    String[] names = ctx.getResources().getStringArray(R.array.nameOfTags);
					    for(int j= 0 ; j< tags.length; j++) {
					    	if (!row.isNull(tags[j])) {
					    		if (tags[j].equals("distance")) {
					    			int distance = Integer.valueOf(row.getString(tags[j]));
            	    				String distanceInMeters = ctx.getResources().getQuantityString(R.plurals.distanceInMeters, 
            	    						distance, distance);
            	    				SpeechHandler.ttsQueue(names[j] + " " + distanceInMeters, 1, 1);
					    		} else {
	            	    	 		SpeechHandler.ttsQueue(names[j] + " " + row.getString(tags[j]), 1, 1);
	            	    	 	}
	            	    	}
			            }
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
	    	} else {
	    		SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.photoNoMetaData), 1, 1);
	    	}
		}
    }
	
    private static final String fromBaseCharacters(final String sText) {
    	int i=0, len=sText.length();
        char c;
        StringBuffer sb = new StringBuffer(len);
        while (i < len) {
            c = sText.charAt(i++);
            if (c == '\\') {
                if (i < len) {
                    c = sText.charAt(i++);
                    if (c == 'u') {
                        c = (char) Integer.parseInt(sText.substring(i, i+4), 16);
                        i += 4;
                    } // add other cases here as desired...
                }
            } // fall through: \ escapes itself, quotes any character but u
            sb.append(c);
        }
        return sb.toString();
    }
}
